package com.xjy.rpc.netty.handler;
/**
 * @description: 消息编码handler
 * @author XJY
 * @date 2024/10/21 9:10
 * @version 1.0
 */
import com.alibaba.fastjson.JSON;
import com.xjy.rpc.netty.message.RpcMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class RpcEncoder extends MessageToByteEncoder<RpcMessage> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, RpcMessage msg, ByteBuf byteBuf) throws Exception {
        //写入消息信息
        byteBuf.writeShort(msg.getMagic());
        byteBuf.writeShort(msg.getMessageType());
        byteBuf.writeLong(msg.getRequestId());
        //序列化 body数据写入缓冲
        byte[] bytes = JSON.toJSONBytes(msg.getBody());
        byteBuf.writeInt(bytes.length);
        byteBuf.writeBytes(bytes);
    }
}
